package org.ttitfly.workflow.handler;

import java.util.ArrayList;
import java.util.List;

/**
 * 链表式处理程序调用器
 * 
 * @author 潘海春
 * @version 2009-8-31
 */
public class ListHandlerInvocation implements HandlerInvocation {

	/**
	 * 处理器
	 */
	private List<Handler> handlers = new ArrayList<Handler>();

	/**
	 * 当前处理器的下标
	 */
	private int currentHandlerIndex = -1;

	/**
	 * 构造函数
	 * 
	 */
	public ListHandlerInvocation() {
	}

	/**
	 * 构造函数
	 * 
	 * @param handler
	 */
	public ListHandlerInvocation(Handler handler) {
		add(handler);
	}

	/**
	 * 构造函数
	 * 
	 * @param handlers
	 * @param eventObject
	 */
	public ListHandlerInvocation(List<Handler> handlers) {
		for (Handler handler : handlers) {
			add(handler);
		}
	}

	/**
	 * add handler
	 * 
	 * @param handler
	 */
	protected void add(Handler handler) {
		if (handler == null) {
			throw new IllegalArgumentException("参数[handler]不能为空！");
		}
		handlers.add(handler);
	}

	@Override
	public Object proceed() throws Exception {
		if (handlers == null || handlers.size() == 0) {
			return null;
		}
		if (currentHandlerIndex == handlers.size() - 1) {
			return null;
		}
		return currentHandler().handle(this);
	}

	/**
	 * 获取当前的处理程序
	 * 
	 * @return
	 */
	protected Handler currentHandler() {
		return handlers.get(++currentHandlerIndex);
	}

}
